/**
 * @Title: BrowserActivity.java
 * @Package: com.jason.fingerprint.ui
 * @Descripton: TODO
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年11月14日 下午3:33:45
 * @Version: V1.0
 */
package com.jason.fingerprint.ui;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.util.DisplayMetrics;
import android.webkit.*;
import org.kymjs.aframe.ui.BindView;
import org.kymjs.aframe.ui.KJActivityManager;
import org.kymjs.aframe.ui.activity.BaseActivity;
import org.kymjs.aframe.utils.StringUtils;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebSettings.RenderPriority;
import android.widget.Button;
import android.widget.TextView;

import com.jason.fingerprint.R;
import com.jason.fingerprint.widget.ProgressWebView;

/**
 * @ClassName: BrowserActivity
 * @Description: 浏览器
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年11月14日 下午3:33:45
 */
public class BrowserActivity extends BaseActivity {
	
	private static final String TAG = "BrowserActivity";
	public static final String BROWSER_URL = "browser_url";
	public static final String BROWSER_TITLE = "browser_title";
	
	@BindView(id = R.id.header_back, click = true)
	private Button mBackButton;
	@BindView(id = R.id.header_title)
	private TextView mTitleTextView;
	@BindView(id = R.id.browser_webview)
	private ProgressWebView mProgressWebView;
	private WebSettings webSettings;
	
	private String mUrl;
	private String mTitle;

	/* (non-Javadoc)
	 * @see org.kymjs.aframe.ui.activity.I_KJActivity#setRootView()
	 */
	@Override 
	public void setRootView() {
		// TODO Auto-generated method stub
		setContentView(R.layout.activity_browser);
	}
	
	/* (non-Javadoc)
	 * @see org.kymjs.aframe.ui.activity.KJFrameActivity#initWidget()
	 */
	@Override
	protected void initWidget() {
		// TODO Auto-generated method stub
		super.initWidget();
		initWebView();
	}
	
	@SuppressLint("SetJavaScriptEnabled") @SuppressWarnings("deprecation")
	private void initWebView() {

//		mProgressWebView.getSettings().setJavaScriptEnabled(true);
//		mProgressWebView.getSettings().setRenderPriority(RenderPriority.HIGH);
//		mProgressWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);  //设置 缓存模式
//        // 开启 DOM storage API 功能
//		mProgressWebView.getSettings().setDomStorageEnabled(true);
//        //开启 database storage API 功能
//		mProgressWebView.getSettings().setDatabaseEnabled(true);
//		mProgressWebView.setDownloadListener(new DownloadListener(){
//
//			@Override
//			public void onDownloadStart(String url, String userAgent,
//					String contentDisposition, String mimetype,
//					long contentLength) {
//				// TODO Auto-generated method stub
//				if (url != null && (url.startsWith("http://") || url.startsWith("https://"))) {
//					startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
//				}
//			}
//
//		});
//
//		mProgressWebView.setWebViewClient(new WebViewClient(){
//
//			/* (non-Javadoc)
//			 * @see android.webkit.WebViewClient#shouldOverrideUrlLoading(android.webkit.WebView, java.lang.String)
//			 */
//			@Override
//			public boolean shouldOverrideUrlLoading(WebView view, String url) {
//				// TODO Auto-generated method stub
//				// 重写此方法表明点击网页里面的链接还是在当前的webview里跳转，不跳到浏览器那边
//				view.loadUrl(url);
//				return true;
//			}
//
//		});
		webSettings = mProgressWebView.getSettings();
		webSettings.setAppCacheEnabled(true);
		webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
		webSettings.setUseWideViewPort(true);
		webSettings.setLoadWithOverviewMode(true);
		webSettings.setDefaultTextEncodingName("utf-8");

		webSettings.setJavaScriptEnabled(true);
		webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
		webSettings.setBuiltInZoomControls(false);// support zoom
		webSettings.setSupportZoom(false);

		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		int screenDensity = metrics.densityDpi;

		Log.i(TAG, "screenDensity = " + screenDensity);
		if (screenDensity == DisplayMetrics.DENSITY_LOW) {
			webSettings.setDefaultZoom(WebSettings.ZoomDensity.CLOSE);
		} else if (screenDensity == DisplayMetrics.DENSITY_MEDIUM) {
			webSettings.setDefaultZoom(WebSettings.ZoomDensity.MEDIUM);
		} else if (screenDensity == DisplayMetrics.DENSITY_HIGH) {
			webSettings.setDefaultZoom(WebSettings.ZoomDensity.FAR);
		} else if (screenDensity == DisplayMetrics.DENSITY_XHIGH) {
			webSettings.setDefaultZoom(WebSettings.ZoomDensity.FAR);
		} else if (screenDensity == DisplayMetrics.DENSITY_XXHIGH) {
			webSettings.setDefaultZoom(WebSettings.ZoomDensity.FAR);
		}

		if (android.os.Build.VERSION.SDK_INT <= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
			// 提高加载渲染优先级
			webSettings.setRenderPriority(RenderPriority.HIGH);
		}
		// 启用缓存
		// 设置 缓存模式
		webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
		webSettings.setNeedInitialFocus(false);

		/*
		 * WebView默认用系统自带浏览器处理页面跳转。 为了让页面跳转在当前WebView中进行，重写WebViewClient。
		 * 但是按BACK键时，不会返回跳转前的页面，而是退出本Activity。重写onKeyDown()方法来解决此问题。
		 */
		mProgressWebView.setWebViewClient(new WebViewClient() {
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				view.loadUrl(url);// 使用当前WebView处理跳转
				return true;// true表示此事件在此处被处理，不需要再广播
			}

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				// TODO Auto-generated method stub
				super.onPageStarted(view, url, favicon);
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				// 页面跳转结束后被回调
				if (mProgressWebView != null) {
					mProgressWebView.setVisibility(View.VISIBLE);
				}
			}

			@Override
			public void onReceivedError(WebView view, int errorCode,
										String description, String failingUrl) {
			}
		});

		/*
		 * 当WebView内容影响UI时调用WebChromeClient的方法
		 */
		mProgressWebView.setWebChromeClient(new WebChromeClient() {

			@Override
			public boolean onJsAlert(WebView view, String url, String message,
									 final JsResult result) {
				// 用Android组件替换
				new AlertDialog.Builder(BrowserActivity.this)
						.setTitle("提示")
						.setMessage(message)
						.setPositiveButton(android.R.string.ok,
								new AlertDialog.OnClickListener() {
									public void onClick(DialogInterface dialog,
														int which) {
										result.confirm();
									}
								}).setCancelable(false).create().show();
				return true;
			}
		});
    }  
	
	/* (non-Javadoc)
	 * @see org.kymjs.aframe.ui.activity.KJFrameActivity#initData()
	 */
	@Override
	protected void initData() {
		// TODO Auto-generated method stub
		super.initData();
		Intent intent = getIntent();
		if (intent != null) {
			mUrl = intent.getStringExtra(BROWSER_URL);
			mTitle = intent.getStringExtra(BROWSER_TITLE);
			mTitleTextView.setText(mTitle);
			Log.i(TAG, "mUrl:" + mUrl);
			mProgressWebView.loadUrl(mUrl);
//			if (!StringUtils.isEmpty(mUrl) && (mUrl.startsWith("http://") || mUrl.startsWith("https://"))) {
//				new Thread(new Runnable() {
//
//					@Override
//					public void run() {
//						mProgressWebView.loadUrl(mUrl);
//						// TODO Auto-generated method stub
//
//					}
//				}).run();
//			}
		}
	}
	
	/* (non-Javadoc)
	 * @see org.kymjs.aframe.ui.activity.KJFrameActivity#widgetClick(android.view.View)
	 */
	@Override
	public void widgetClick(View v) {
		// TODO Auto-generated method stub
		super.widgetClick(v);
		switch (v.getId()) {
		case R.id.header_back:
			KJActivityManager.create().finishActivity(this);
			break;

		default:
			break;
		}
	}
	
	/* (non-Javadoc)
	 * @see org.kymjs.aframe.ui.activity.BaseActivity#onKeyDown(int, android.view.KeyEvent)
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && mProgressWebView.canGoBack()) {
			mProgressWebView.goBack();
			return true;
		}
		return false;
	}

}
